package org.openfans.domain.logic;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.Tag;
import org.openfans.domain.TagRelation;
import org.openfans.util.ThreadFans;

public class TagRelationManager {
	private Facade facade;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	/**
	 * 功能说明：<br>
	 * 创建者：张俊<br>
	 * 创建时间：2006-5-29<br>
	 * 
	 * @param tag
	 * @param tagTitleStr
	 */
	public void addRelations(Tag tag, String tagTitleStr) {
		String[] tagTitles = tagTitleStr.split(" ");
		Fans fans = facade.getFans(ThreadFans.get().getFansId());
		for (int i = 0; i < tagTitles.length; i++) {
			addRelation(fans, tag, tagTitles[i].trim());
		}
		// 增加用户对此tag的使用，只加一次
		facade.addFansTag(fans, tag);
	}

	private void addRelation(Fans fans, Tag tag, String relationTagTitle) {
		if (relationTagTitle.length() == 0
				|| tag.getTitle().equals(relationTagTitle)) {
			return;
		}
		Tag rtag = facade.getTagByTitle(relationTagTitle);

		if (null == rtag) {// 新增tag，肯定没有关联
			rtag = facade.addNewTagByTitle(fans, relationTagTitle);
			addRelation(tag, rtag);
		} else {
			if (tag.getTagRelations() == null
					|| getTagRelation(tag, rtag) == null) {
				addRelation(tag, rtag);
			} else {
				facade.save(getTagRelation(tag, rtag).increaseWeight(2));
				facade.save(getTagRelation(rtag, tag).increaseWeight(1));
			}
		}
		// 增加用户的tag
		facade.addFansTag(fans, rtag);
	}

	private void addRelation(Tag tag, Tag rtag) {
		// 正向权重+2;
		TagRelation tr = new TagRelation(tag, rtag, 2);
		facade.save(tr);
		// 反向权重+1;
		TagRelation tr1 = new TagRelation(rtag, tag, 1);
		facade.save(tr1);
	}

	private TagRelation getTagRelation(Tag tag, Tag rtag) {
		for (TagRelation tr : tag.getTagRelations()) {
			if (tr.getRtag().getTagId() == rtag.getTagId()) {
				return tr;
			}
		}
		return null;
	}

}
